#!/usr/bin/python

import sys
import os
import re
import shutil


def error_out(msg):
    sys.stderr.write("ERROR: %s\n" % (msg))
    sys.exit(1)

def main():
    try:
        book_dir = sys.argv[1]
        target_dir = sys.argv[2]
    except IndexError:
        sys.stderr.write("Usage: %s BOOK-SRC-DIR TARGET-DIR\n"
                         % (os.path.basename(sys.argv[0])))
        sys.exit(1)

    # Create the target directory if it doesn't exist, fuss otherwise.
    if os.path.exists(target_dir):
        error_out("Target directory '%s' already exists" % (target_dir))

    # Copy all the versioned files in the book directory into the target
    # directory.
    print "Exporting book source into '%s'" % (target_dir)
    os.system('svn export "%s" "%s"' % (book_dir, target_dir))

    print "Copying version.xml into place"
    shutil.copy(os.path.join(book_dir, 'version.xml'),
                os.path.join(target_dir, 'version.xml'))

    # Read book.xml to get the mapping of section filenames to section
    # entities.
    print "Parsing book.xml file to find entity-to-filename map"
    book_xml_file = os.path.join(target_dir, 'book.xml')
    try:
        lines = open(book_xml_file).readlines()
    except Exception, e:
        error_out("Unable to read '%s' (%s)" % (book_xml_file, str(e)))

    out_fp = open(book_xml_file, 'w')
    _re_entity = re.compile(r'<!ENTITY ([a-zA-Z0-9]*)\s+SYSTEM "(.*)">')

    for line in lines:
        match = _re_entity.search(line)
        if match:
            new_name = os.path.join(target_dir, match.group(1) + ".xml")
            old_name = os.path.join(target_dir, match.group(2))
            print "Renaming '%s' to '%s'" % (old_name, new_name)
            os.rename(old_name, new_name)
            line = '<!ENTITY %s SYSTEM "%s">\n' % (match.group(1),
                                                   match.group(1) + ".xml")
        out_fp.write(line)
        
if __name__ == "__main__":
    main()
